<template>
  <div>
    <BasicModal
      @register="edgeRegisterModal"
      v-bind="$attrs"
      :helpMessage="['提示1', '提示2']"
      @ok="addEdge"
    >
      <BasicForm @register="addEdgeRegisterForm" />
    </BasicModal>
    <EdgeCreated @register="edgeCreatedModal" />
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { getEdgeTypeList } from '/@/api/thingsborad/edge/edge';
  import { getTheEdgeData } from '/@/api/thingsborad/edge/edge';
  import { onMounted, ref } from 'vue';
  import { message } from 'ant-design-vue';
  import { addTheEdge } from '/@/api/thingsborad/edge/edge';
  import EdgeCreated from './EdgeCreated.vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useModal } from '/@/components/Modal';

  const emits = defineEmits(['closeAddEdgeFlag']);
  // 边缘管理类型
  let edgeManagementList = ref<Array<any>>([]);
  let addSchemas: FormSchema[] = [
    {
      field: 'addEdgeName',
      component: 'Input',
      label: '名称',
      required: true,
      componentProps: {
        placeholder: '请输入仓库 名称',
      },
    },
    {
      field: 'edgeType',
      component: 'Select',
      label: '边缘类型',
      required: true,
      componentProps: {
        mode: 'tags',
      },
    },
    {
      field: 'edgeKey',
      component: 'Input',
      label: '边缘键',
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'edgePassword',
      component: 'Input',
      label: '边缘密钥',
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'label',
      component: 'Input',
      label: '标签',

      componentProps: {
        placeholder: '请输入标签',
      },
    },
    {
      field: 'describe',
      component: 'InputTextArea',
      label: '说明',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入说明',
      },
    },
  ];
  let edgeKeyValue = ref<string>();
  let edgePasswordValue = ref<string>();
  let edgeData = ref<any>();
  let isEdit = ref<boolean>(false);
  onMounted(() => {
    getEdgeTypeDataList();
  });
  const [edgeCreatedModal, { openModal: edgeCreatedOpenModal, setModalProps }] = useModal();
  // 表单初始化
  const [addEdgeRegisterForm, { validate, updateSchema, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas: addSchemas,
    showSubmitButton: true,
    showResetButton: false,
    ...modalFormStyleSetting,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
  });
  const [edgeRegisterModal, { closeModal: closeAddEdgeModal, setModalProps: closeSetModalProps }] =
    useModalInner(async (data) => {
      

      //获取边缘类型下拉数据
      getEdgeTypeDataList();
      // 编辑编辑
      if ('record' in data) {
        const theEdgeData = await getTheEdgeData(data.record.id);
        edgeData.value = theEdgeData;
        isEdit.value = true;

        setFieldsValue({
          addEdgeName: theEdgeData.name,
          edgeType: theEdgeData.type,
          label: theEdgeData.label,
          describe: theEdgeData.additionalInfo.description,
          edgePassword: theEdgeData.secret,
          edgeKey: theEdgeData.routingKey,
        });
      } //添加边缘
      else {
        isEdit.value = false;
        resetFields();
        setFieldsValue({
          edgeKey: data.key,
          edgePassword: data.password,
        });
      }
      edgeKeyValue.value = data.key;
      edgePasswordValue.value = data.key;
      updateSchema({
        field: 'edgeType',
        componentProps: {
          options: edgeManagementList.value,
        },
      });
      closeSetModalProps({
        loading: false,
        confirmLoading: false,
        ...modalStyleSetting,
        width: '800px',
      });
    });
  //获取边缘类型
  async function getEdgeTypeDataList() {
    edgeManagementList.value = [];
    try {
      const edgeTypeListData = await getEdgeTypeList();

      edgeTypeListData.forEach((item) => {
        edgeManagementList.value.push({
          label: item.type,
          value: item.type,
        });
      });
    } catch (e) {}
  }
  // 添加 边缘
  async function addEdge() {
    try {
      const inputValue = await validate();
      
      
      let edgeType: string;

      if (typeof inputValue.edgeType === 'object') {
        if (inputValue.edgeType.length > 1) {
          message.warning('边缘类型只能选择一个');
          return;
        } else {
          edgeType = inputValue.edgeType[0];
        }
      } else {
        edgeType = inputValue.edgeType;
      }

      let params: any;
      if (isEdit.value) {
        edgeData.value.name = inputValue.addEdgeName;
        edgeData.value.type = edgeType;
        edgeData.value.label = inputValue.label;
        edgeData.value.routingKey = inputValue.edgeKey;
        edgeData.value.secret = inputValue.edgePassword;
        edgeData.value.additionalInfo = {
          description: inputValue.describe,
        };
        params = edgeData.value;
      } else {
        params = {
          name: inputValue.addEdgeName,
          type: edgeType,
          label: inputValue.label,
          routingKey: inputValue.edgeKey,
          secret: inputValue.edgePassword,
          additionalInfo: {
            description: inputValue.describe,
          },
        };
      }

      const edgeDataFlag = await addTheEdge(params);
      // 清空表格
      await resetFields();
      // 组件通信 提示父组件弹窗关闭
      emits('closeAddEdgeFlag', true);
      edgeCreatedOpenModal(true, edgeDataFlag);
      // 关闭弹窗
      closeAddEdgeModal();
      setModalProps({
        title: '边缘已创建！检查安装和连接说明',
        showOkBtn: false,
        width: '800px',
      });
    } catch (e) {}
  }
</script>
